<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="类型名称" prop="typeName">
        <el-input
          v-model="queryParams.typeName"
          placeholder="请输入类型名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['heima:newsType:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['heima:newsType:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['heima:newsType:remove']"
        >删除</el-button>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="newsTypeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="新闻类型ID" align="center" prop="typeId" />
      <el-table-column label="类型名称" align="center" prop="typeName" />
      <el-table-column label="父类型ID" align="center" prop="parentId" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['heima:newsType:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['heima:newsType:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改新闻类型对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="类型名称" prop="typeName">
          <el-input v-model="form.typeName" placeholder="请输入类型名称" />
        </el-form-item>
        <el-form-item label="父类型" prop="parentId">
          <el-select v-model="firstTypeId" placeholder="一级类型（可选）" clearable :disabled="firstSelectDisabled" @change="changeFirstType">
            <el-option
              v-for="dict in firstTypeList"
              :key="dict.name"
              :label="dict.name"
              :value="dict.value"
            />
          </el-select>
          <el-select v-model="secondTypeId" placeholder="二级类型（可选）" :disabled="secondSelectDisabled" clearable>
            <el-option
              v-for="dict in secondTypeList"
              :key="dict.name"
              :label="dict.name"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listNewsType, getNewsType, delNewsType, addNewsType, updateNewsType, getAllNewsType } from "@/api/heima/newsType";

export default {
  name: "NewsType",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 新闻类型表格数据
      newsTypeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        typeName: null,
        parentId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      //整棵新闻类型树
      typeDataArray: [],
      // 一级新闻分类
      firstTypeList: [],
      // 二级新闻分类
      secondTypeList: [],
      // 一级新闻分类ID
      firstTypeId: null,
      // 二级新闻分类ID
      secondTypeId: null,
      //一级下拉框是否禁用
      firstSelectDisabled: false,
      //二级下拉框是否禁用
      secondSelectDisabled: false

    };
  },
  created() {
    this.getList();

    //构建新闻类型
    this.buildNewsTypeTree();
  },
  methods: {
    /** 查询新闻类型列表 */
    getList() {
      this.loading = true;
      listNewsType(this.queryParams).then(response => {
        this.newsTypeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        typeId: null,
        typeName: null,
        parentId: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.firstTypeId = null;
      this.secondTypeId = null;
      this.secondTypeList = [];

        this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.typeId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加新闻类型";

    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const typeId = row.typeId || this.ids
      getNewsType(typeId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改新闻类型";
        //处理一二级类型回显
        let typeId = this.form.typeId;
        let thirdTypeId = '';
        for (const firstTreeNode of this.typeDataArray) {
          if (firstTreeNode.value === typeId) {
            this.firstTypeId = null;
            this.secondTypeId = null;
            this.secondTypeList = [];
            this.firstSelectDisabled = true;
            this.secondSelectDisabled = true;
            break;
          }
          for (const secondTreeNode of firstTreeNode.children) {
            if (secondTreeNode.value === typeId) {
              this.firstTypeId = firstTreeNode.value;
              this.secondTypeId = null;
              this.firstSelectDisabled = false;
              this.secondSelectDisabled = true;
              break;
            }
            for (const thirdTreeNode of secondTreeNode.children) {
              if (thirdTreeNode.value === typeId) {
                this.firstTypeId = firstTreeNode.value;
                this.secondTypeId = secondTreeNode.value;
                this.firstSelectDisabled = false;
                this.secondSelectDisabled = false;
                this.changeFirstType();
                thirdTypeId = typeId;
                break;
              }
            }
          }
        }

      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        //处理父类型
        if (this.secondTypeId != null) {
          this.form.parentId = this.secondTypeId;
        } else if (this.firstTypeId != null) {
          this.form.parentId = this.firstTypeId;
        } else {
          this.form.parentId = 0;
        }

        if (valid) {
          if (this.form.typeId != null) {
            updateNewsType(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addNewsType(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const typeIds = row.typeId || this.ids;
      this.$modal.confirm('是否确认删除新闻类型编号为"' + typeIds + '"的数据项？').then(function() {
        return delNewsType(typeIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 选择一级分类之后加载二级分类 */
    changeFirstType(){
      this.typeDataArray.forEach(item=>{
        if(item.value===this.firstTypeId){
          this.secondTypeList=item.children;
        }
      })
    },
    /** 构建新闻类型树对象 */
    buildNewsTypeTree() {
      getAllNewsType().then(response => {
        const dataList = response;

        // 使用Map存储每个节点，方便查找父节点
        const nodeMap = new Map();

        // 遍历数据列表，创建节点并添加到Map中
        for (const data of dataList) {
          const typeId = data.typeId;
          const typeName = data.typeName;
          const parentId = data.parentId;

          const node = { name: typeName, value: typeId, children: [] };
          nodeMap.set(typeId, node);

          if (parentId === 0) {
            // 根节点
            this.typeDataArray.push(node);
            this.firstTypeList.push(node);
          } else {
            // 非根节点，添加到父节点的子节点列表中
            const parent = nodeMap.get(parentId);
            parent.children.push(node);
          }
        }

      });

    }
  }
};
</script>
